package com.wlit.print;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.callback.CefQueryCallback;
import org.cef.handler.CefMessageRouterHandler;

import javax.swing.*;

public class LabelPrintDataHandler implements CefMessageRouterHandler {

    private static final Logger logger = Logger.getLogger(LabelPrintDataHandler.class);

    @Override
    public boolean onQuery(CefBrowser cefBrowser, CefFrame cefFrame, long l, String s, boolean b, CefQueryCallback cefQueryCallback) {
        if (s == null || s.length() == 0){
            showMessage("打印数据为空");
            return true;
        }

        JSONArray jsonArray = null;
        try {
             jsonArray = JSONArray.parseArray(s);
        }catch (Exception e){
            e.printStackTrace();
        }

        if (jsonArray == null){
            showMessage("打印数据格式错误");
            return true;
        }

        if (!LabelPrinter.getInstance().isOpen()) {
            showMessage("打印机未连接，请先连接打印机");
            return true;
        }

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject printInfo = jsonArray.getJSONObject(i);
            logger.info("打印标签:" + printInfo);
            LabelPrinter.getInstance().print(printInfo);
        }

        cefQueryCallback.success("已提交打印");
        return true;
    }

    @Override
    public void onQueryCanceled(CefBrowser cefBrowser, CefFrame cefFrame, long l) {

    }

    @Override
    public void setNativeRef(String s, long l) {

    }

    @Override
    public long getNativeRef(String s) {
        return 0;
    }

    private void showMessage(String message){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(null, message);
            }
        });
    }
}
